import 'dart:async';
import 'dart:io';

import 'package:app_im/im_init.dart';
import 'package:app_map/app_map.dart';
import 'package:app_network/app_network.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_error_catch/flutter_error_catch.dart';
import 'package:flutter_overlay_kit/toast/toast_util.dart';
import 'package:tsdemo_player/tsdemo_player.dart';
import 'package:tsdemo/bean/space_user_info.dart';
import 'package:tsdemo/common/constants.dart';
import 'package:tsdemo/http/Network/Loading.dart';
import 'package:tsdemo/route/lib/route_configer.dart';
import 'package:tsdemo/route/route_delegate.dart';
import 'package:tsdemo/route/route_manager.dart';
import 'package:tsdemo/common/route_manager.dart' as old;
import 'package:app_service_user/app_service_user.dart';
import 'package:tsdemo/ui/class/crowdFounding/order_confirm_page.dart';
import 'package:tsdemo/ui/class/login/login_page.dart';
import 'package:tsdemo/ui/class/mine/order/model/order_get_share_order_model.dart';
import 'http/Network/Api.dart';
import 'http/Network/UrlPath.dart';
import 'module/tsdemo/tsdemo_detail/model/tsdemo_detail_model.dart';
import 'ui/app.dart';
import 'package:flutter_bugly/flutter_bugly.dart';
import './main_init/main_init.dart';
import 'ui/class/goods/model/good_detail_model/goods_detail_model_new.dart';
import 'ui/class/tsdemoTurntable/turntable_help_page.dart';

void main222() => runZonedGuarded(() {}, (e, s) {
      debugPrint(e);
    });

void main() {
  FlutterBugly.postCatchedException(() {
    appMain();
  });
}

void appMain() {
  // 强制竖屏
  WidgetsFlutterBinding.ensureInitialized(); //必须要添加这个进行初始化 否则下面会错误

  PluginUtil.initMap(BAIDUMAP_APPID_IOS);

  GlobalKey<NavigatorState> globalKey = GlobalKey<NavigatorState>();
  MainInit.initWithGlobalKey(
      globalKey, PackageType.preproduct, PackageTargetType.pgyer);

  // 初始化路由
  RouteConfiger.configureRoutes(RouteManager.router);
  RouteManager.navigatorKey = globalKey;
  RouteManager.delegate = RouteDelegate()
    // scheme拦截
    ..shouldJumpPage = ({
      BuildContext context,
      String url,
      String pageName,
      Map<String, dynamic> arguments,
    }) {
      debugPrint('-----shouldJumpPage pageName=$pageName');
      if (pageName == RouteNames.lotteryTurntablePage &&
          TurnTableHelpPage.isPageShowing == true) {
        return false;
      }
      if (pageName == RouteNames.createGuessWishPage) {
        _handleJumpCreateGuessWishPage(context, url, arguments);
        return false;
      }
      if (pageName == RouteNames.tsdemoListDetailPage) {
        _handleJumpWishListDetailPage(context, url, arguments);
        return false;
      }
      //跳转订单详情
      if (pageName == RouteNames.orderDetailPage) {
        _handleJumpOrderDetailPage(context, url, arguments);
        return false;
      }
      //请ta买进入 name为不存在的helpToPayOrder 自定义获取内容详情再进入
      if (pageName == 'helpToPayOrder') {
        _handleJumpOrderConfirmPage(context, url, arguments);
        return false;
      }
      //请ta买进入 name为不存在的helpToPayOrder 自定义获取内容详情再进入
      if (pageName == 'orderConfirmPage') {
        _handleJumpCrowdOrderConfirmPage(context, url, arguments);
        return false;
      }

      return true;
    }
    // 应用内push页面
    ..shouldPushPage = ({
      BuildContext context,
      String pageName,
      Map<String, dynamic> arguments,
    }) {
      debugPrint('-----shouldPushPage pageName=$pageName');
      if (pageName == RouteNames.loginPage) {
        if (login_page.isPageShowing == true) {
          return false;
        }
        login_page.isPageShowing = true;
      }
      return true;
    };

  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
      .then((_) {
    AppCatchError.run(const AppWithIM(child: MyApp()));
  });

  configLoading();

  if (Platform.isAndroid) {
    // 以下两行 设置android状态栏为透明的沉浸。写在组件渲染之后，是为了在渲染后进行set赋值，覆盖状态栏，写在渲染之前MaterialApp组件会覆盖掉这个值。
    SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      // systemNavigationBarIconBrightness: Brightness.light,
      // statusBarIconBrightness: Brightness.dark,
      // statusBarBrightness: Brightness.light,
    );
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }
  // 设置视频缓存大小
  SuperPlayerPlugin.setGlobalCacheFolderPath("video_cache");
  SuperPlayerPlugin.setGlobalMaxCacheSize(200);
}

_handleJumpCreateGuessWishPage(
  BuildContext context,
  String url,
  Map<String, dynamic> arguments,
) {
  if (UserInfoManager.isLoginState) {
    Api.joinGuessGame({
      "code": arguments["code"],
      "gameId": arguments["id"],
    }).then((ResultData data) {
      if (data.isSuccess) {
        if (data.data != null) {
          RouteManager.pushPage(context, RouteNames.guessWishWaitBeginPage,
              arguments: {
                "gameId": data.data["gameId"],
                "onlook": data.data["onlook"],
              });
        }
      } else {
        if (data.code == 1009) {
          ToastUtil.showMessage(data.msg);
        } else {
          RouteManager.pushPage(context, RouteNames.guessWishResultPage,
              arguments: {
                "id": arguments["id"],
              });
        }
      }
    });
  } else {
    pushLogin(context, url, arguments);
  }
}

_handleJumpWishListDetailPage(
  BuildContext context,
  String url,
  Map<String, dynamic> arguments,
) {
  if (UserInfoManager.isLoginState) {
    bool isMe = arguments["buyerId"] == UserInfoManager.instance.userModel.id;
    arguments["isMe"] = isMe;
    RouteManager.pushPage(
      context,
      RouteNames.tsdemoListDetailPage,
      arguments: arguments,
    );
  } else {
    pushLogin(context, url, arguments);
  }
}

_handleJumpOrderDetailPage(
  BuildContext context,
  String url,
  Map<String, dynamic> arguments,
) {
  if (UserInfoManager.isLoginState) {
    // String payInfoId = widget.payInfoId;
    // String bizId = widget.detailModel.bizId;
    // String buyerId = _detailModel.buyerId;
    // String consigneeAccountId = _detailModel.consigneeAccountId;

    //跳转订单详情页面
    bool isSend = false;
    String payInfoId;
    String bizId;
    String buyerId = arguments["buyerId"] ?? "";
    String consigneeAccountId = arguments["consigneeAccountId"] ?? "";
    if (UserInfoManager.instance.userModel.id != null) {
      if (UserInfoManager.instance.userModel.id == buyerId) {
        isSend = true;
        payInfoId = arguments["payInfoId"] ?? "";
        bizId = null;
      } else if (UserInfoManager.instance.userModel.id == consigneeAccountId) {
        isSend = false;
        payInfoId = arguments["payInfoId"] ?? "";
        bizId = null;
      } else {
        isSend = false;
        payInfoId = null;
        bizId = arguments["bizId"] ?? "";
      }
    }
    RouteManager.pushPage(context, RouteNames.orderDetailPage,
        // bool isSend;
        // String payInfoId;
        // String bizId;
        arguments: {
          "isSend": isSend,
          "payInfoId": payInfoId,
          "bizId": bizId,
        });
  } else {
    pushLogin(context, url, arguments);
  }
}

//从请ta买h5进入的页面 - 跳转至订单确认页
_handleJumpOrderConfirmPage(context, url, arguments) {
  debugPrint(arguments);
  if (UserInfoManager.isLoginState) {
    Api.tsdemoGetDetail({
      "tsdemoId": arguments["tsdemoId"],
    }).then((ResultData data) {
      WishDetailModel detailWishModel = WishDetailModel.fromJson(data.data);
      List<Items> items = [];
      for (var element in detailWishModel.items) {
        items.add(element);
      }
      if (UserInfoManager.instance.userModel.id != detailWishModel.buyerId) {
        old.RouteManager.pushToRoute(
          context,
          OrderConfirmPagePage(
            detailWishModel: detailWishModel,
            detailWishGoodsItem: items,
            typeIndex: 3,
            tsdemoID: detailWishModel.id,
            detailModel: null,
          ),
        );
      } else {
        //本应该跳转到请ta买页面 但是目前没有订单id 先不做跳转 停留在首页 - 2022-07-22
        // old.RouteManager.pushToRoute(
        //   context,
        //   GoodsShareTaPage(
        //     detailModel: detailWishModel,
        //     detailWishGoodsItem: items,
        //     typeIndex: 3,
        //     tsdemoID: detailWishModel.id,
        //   ),
        // );
      }
    });
  } else {
    pushLogin(context, url, arguments);
  }
}

//从众筹详情 - h5进入的页面 - 跳转至众筹（aa）订单确认页
_handleJumpCrowdOrderConfirmPage(context, url, arguments) {
  debugPrint(arguments);
  if (UserInfoManager.isLoginState) {
    AppNetworkKit.get(
      UrlPath.tsdemoGiftOrderGetShareOrderDetail,
      params: {"orderId": arguments["bizId"]},
    ).then((ResponseModel responseModel) {
      OrderGetShareOrderModel shareOrderInfo =
          OrderGetShareOrderModel.fromJson(responseModel.result);
      SpecCombinationInfoList sKU = shareOrderInfo.goodsInfoList.first;
      Goods_detail_model detailModel = Goods_detail_model.initData(
        goodsName: sKU.goodsName,
        marketPriceStr: sKU.salePriceStr,
        salePriceStr: (sKU.snapshotPrice / 100).toStringAsFixed(2),
        mainImgUrl: sKU.imageUrl,
      );
      detailModel.goodsNum = sKU.number;
      detailModel.selectSKU = sKU;
      detailModel.selectSKU.salePrice = sKU.snapshotPrice ~/ sKU.number;
      detailModel.selectSKU.salePriceStr =
          ((sKU.snapshotPrice ~/ sKU.number) / 100).toStringAsFixed(2);
      detailModel.salePrice = sKU.snapshotPrice ~/ sKU.number;

      SpaceUserInfo userInfo = SpaceUserInfo.fromJson({
        "nickname": shareOrderInfo.nickName,
        "avatar": shareOrderInfo.avatar ?? '',
        "accountId": '',
      });
      if (shareOrderInfo.remainNum == 0) {
        return ToastUtil.showMsg('该众筹单已结束', context);
      } else {
        old.RouteManager.pushToRoute(
          context,
          OrderConfirmPagePage(
            bizid: shareOrderInfo.orderId,
            finishNum: shareOrderInfo.shareNum - shareOrderInfo.remainNum,
            remainNum: shareOrderInfo.shareNum,
            detailModel: detailModel,
            userInfo: userInfo,
            typeIndex: 0,
          ),
        );
      }
    });
  } else {
    pushLogin(context, url, arguments);
  }
}

//跳向登陆
pushLogin(context, url, arguments) {
  RouteManager.pushPage(context, RouteNames.loginPage, arguments: {
    "loginCallback": () {
      _handleJumpCreateGuessWishPage(
        context,
        url,
        arguments,
      );
    }
  });
}

void configLoading() {
  Loading.config();
  return;
}
